package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;


    @Override
    public Page<Order> findWithOrder(Integer pageNum, Integer pageSize, Long number, Date beginTime, Date endTime) {
       LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.like(number != null ,Order::getId,number)
                    .gt(beginTime != null,Order::getOrderTime,beginTime)
                    .lt(endTime != null,Order::getOrderTime,endTime);
       Page<Order> page = new Page<>(pageNum,pageSize);
        Page<Order> page1 = orderMapper.selectPage(page, queryWrapper);
        return page1;
    }

    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize) {
        User user = UserHolder.get();
        //分页
        Page<Order> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId,user.getId())
                    .orderByDesc(Order::getOrderTime);
//        List<Order> orderList = orderMapper.selectList(queryWrapper);
        Page<Order> page1 = orderMapper.selectPage(page, queryWrapper);
        //查一下
        //要往每个订单里面塞一个orderDetails
        for (Order order : page1.getRecords()) {
            LambdaQueryWrapper<OrderDetail> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(OrderDetail::getOrderId,order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(queryWrapper1);
            order.setOrderDetails(orderDetails);
        }
        return page1;
    }

    @Override
    public void save(Order order) {
        //这个不仅要保存订单，还得保存订单详情
        //找出用户
        User user = UserHolder.get();
        //查出购物车
        List<Cart> cartList = cartService.findAll();
        if (CollectionUtil.isEmpty(cartList)){
            throw new CustomException("购物车为空，不能生成订单");
        }
        //查询地址
        Address address = addressService.findById(order.getAddressId());
        if (address == null){
            throw new CustomException("收货地址不存在,无法生成订单");
        }

        //为了总价好计算，我们先插入订单详情，再插入订单
        //手动生成订单id
        long orderId = IdWorker.getId();
        BigDecimal total = new BigDecimal(0);
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setImage(cart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());

            orderDetailMapper.insert(orderDetail);

            //累加总金额
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }

        //然后插入订单
        //6. 生成订单
        order.setId(orderId);//使用刚刚生成的orderid
        order.setNumber(orderId + "");//订单号 使用订单id
        order.setStatus(0);//待付款
        order.setUserId(user.getId());//登录用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//支付时间(支付的时候再更新一下)
        order.setAmount(total);//本次订单总金额=所有明细中单价*数量再相加
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);

        //7. 清空当前用户购物车
        cartService.clean();

    }
}
